package hk.cic.demointegrationapp;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.JavascriptInterface;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.Spinner;
import android.widget.Switch;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cily.utils.log.BaseWv;
import com.cily.utils.log.L;

import java.util.ArrayList;
import java.util.List;

public class SettingActivity extends AppCompatActivity {
    private BaseWv wv;
    private EditText ed_server;
    private RadioButton rb_face;
    private  RadioButton rb_recode;
    private  RadioButton rb_check;
    private int is_in = 3;
    private ArrayAdapter<String> adapterString;
    private ArrayAdapter<SpinnerOption> adapterContract;
    private List<SpinnerOption> listSpinnerOption = new ArrayList<SpinnerOption>();
    private RadioButton rdobtn_auto;
    private  RadioButton rdobtn_in;
    private  RadioButton rdobtn_out;
    private Spinner spinner_contract;
    private String contract;
    private String j ;
    private String w;
    private String acceptRange ;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_setting);



        ed_server = (EditText)findViewById(R.id.ed_server_id);
        String server = getHostUrl();
        if (server != null && server.trim().length() > 0){
            ed_server.setText(server);
        }

        ed_server.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence text, int start, int before, int count) {
            }

            @Override
            public void beforeTextChanged(CharSequence text, int start, int count,int after) {
            }

            @Override
            public void afterTextChanged(Editable edit) {
                wv.addJavascriptInterface(new SettingActivity.JsToJava(), "androidShare");
            }
        });


        rb_face = (RadioButton)findViewById(R.id.rdobtn_face_id);
        rb_face.setChecked(getIsFace() ==1);

        rb_recode = (RadioButton)findViewById(R.id.rdobtn_recode_id);
        rb_recode.setChecked(getIsFace() == 0);

        rb_check = (RadioButton)findViewById(R.id.rdobtn_check_id);
        rb_check.setChecked(getIsFace() ==3);

        int i = getIsIn();
        rdobtn_auto = (RadioButton)findViewById(R.id.rdobtn_auto_id);
        rdobtn_auto.setChecked(getIsIn() == 3);

        rdobtn_in = (RadioButton)findViewById(R.id.rdobtn_in_id);
        rdobtn_in.setChecked(getIsIn() == 1);

        rdobtn_out = (RadioButton)findViewById(R.id.rdobtn_out_id);
        rdobtn_out.setChecked(getIsIn() == 0);
       // contract= getContract();

        spinner_contract= (Spinner)findViewById(R.id.spinner_contract_id);

        List<String> listSpinnerOptionS = new ArrayList<String>();
        listSpinnerOptionS.add("Synergos UAT Test 01");
        adapterString = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, listSpinnerOptionS);
        adapterString.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner_contract.setAdapter(adapterString);
        wv = (BaseWv)findViewById(R.id.wv_contract_id);
        wv.getSettings().setJavaScriptEnabled(true);

        wv.loadUrl("file:///android_asset/GetContractList.html?host=" + server + "");
        wv.addJavascriptInterface(new SettingActivity.JsToJava(), "androidShare");



//        adapterContract = new ArrayAdapter<SpinnerOption>(this,android.R.layout.simple_spinner_item, listSpinnerOption);
//        adapterContract.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//        spinner_contract.setAdapter(adapterContract);

        findViewById(R.id.btn_server_id).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String hostUrl = ed_server.getText().toString().trim();

                int isFace = 0;
                if(rb_face.isChecked()) {
                    isFace = 1;
                }
                if(rb_recode.isChecked()) {
                    isFace = 0;
                }
                if(rb_check.isChecked()) {
                    isFace = 3;
                }
                if (hostUrl == null || hostUrl.length() < 1){
                    App.getApp().showToast("請輸入服務器地址");
                    return;
                }

                if(rdobtn_auto.isChecked()){
                    is_in = 3;
                }

                if(rdobtn_in.isChecked()){
                    is_in = 1;
                }

                if(rdobtn_out.isChecked()){
                    is_in = 0;
                }


               // contract = ((SpinnerOption)spinner_contract.getSelectedItem()).getValue();
                saveSetting(hostUrl,isFace,is_in, contract, acceptRange,j,w);
                Intent i = new Intent(SettingActivity.this, MainActivity.class);
                startActivity(i);
                finish();
                App.getApp().showToast("設置保存成功");

            }
        });
    }
    private class SettingAdapter extends ArrayAdapter<SpinnerOption>{
        private List<SpinnerOption> datas;

        public SettingAdapter(Context context, List<SpinnerOption> objects) {
            super(context, android.R.layout.simple_spinner_item, objects);
            this.datas = objects;
        }

        @NonNull
        @Override
        public View getView(int position, View v, ViewGroup parent) {
            v = LayoutInflater.from(SettingActivity.this).inflate(android.R.layout.simple_spinner_item, parent, false);
            TextView tv = (TextView)v.findViewById(android.R.id.text1);
            tv.setText(datas.get(position).getText());
            return v;
        }

        @Override
        public int getCount() {
            return datas.size();
        }
    }

    private void BindingSp(List<SpinnerOption> listSpinnerOptions){

        adapterContract = new SettingAdapter(this, listSpinnerOptions);

        adapterContract.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        try
        {
            spinner_contract.setAdapter(adapterContract);
        }catch (Exception e){
            String es = e.getMessage();
        }
    }

    private class JsToJava{
        //这里需要加@JavascriptInterface，4.2之后提供给javascript调用的函数必须带有@JavascriptInterface
        @JavascriptInterface
        public void jsMethod(String paramFromJS){
            JSONArray array = JSONArray.parseArray(paramFromJS);
            List<ContractResultBean> contractResultBeenList = new ArrayList<>();
            for (int i = 0; i < array.size(); i++) {
                JSONObject jsonObject = array.getJSONObject(i);
                ContractResultBean cr = (ContractResultBean) JSONObject.toJavaObject(jsonObject,ContractResultBean.class);
                contractResultBeenList.add(cr);
                listSpinnerOption.add(new SpinnerOption(cr.getContractData_ID(),cr.geContractData_Area()));
            }

            ContractResultBean c =  contractResultBeenList.get(0);
            if (!c.getContractData_Coordinate().isEmpty()) {
                String[] coordinate =c.getContractData_Coordinate().split(",");
                 j = coordinate[0] ;
                 w = coordinate[1];
                acceptRange = c.getContractData_AcceptRange();
            }

        }
    }

    private void saveSetting(String host, int isFace, int in, String contract, String acceptRange, String y, String x){
        SharedPreferences sp = getSharedPreferences("sp_setting", 0);
        SharedPreferences.Editor ed = sp.edit();
        ed.putString("server_host", host);
        ed.putInt("is_face",isFace);
        ed.putInt("is_in",in);
        ed.putString("contract",contract);
        ed.putString("acceptRange",acceptRange);
        ed.putString("y",y);
        ed.putString("x",x);
        ed.commit();
    }

    public String getHostUrl(){
        SharedPreferences sp = getSharedPreferences("sp_setting", 0);
        return sp.getString("server_host", "");
    }

    public String getContract(){
        SharedPreferences sp = getSharedPreferences("sp_setting", 0);
        return sp.getString("contract", "");
    }

    public int getIsFace() {
        SharedPreferences sp = getSharedPreferences("sp_setting", 0);
        return sp.getInt("is_face", 0);
    }

    public int getIsIn() {
        SharedPreferences sp = getSharedPreferences("sp_setting", 0);
        return sp.getInt("is_in", 3);
    }

}
